<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .register-container {
            width: 100%;
            max-width: 500px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }
        
        .register-title {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
            font-size: 24px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-size: 14px;
            font-weight: 500;
        }
        
        .form-input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 15px;
            transition: all 0.3s;
        }
        
        .form-input:focus {
            border-color: #4a90e2;
            box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.2);
            outline: none;
        }
        
        .error-message {
            color: #e74c3c;
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }
        
        .register-btn {
            width: 100%;
            padding: 14px;
            background: #4a90e2;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 10px;
        }
        
        .register-btn:hover {
            background: #3a7bc8;
        }
        
        .loader {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #4a90e2;
            border-radius: 50%;
            width: 16px;
            height: 16px;
            animation: spin 1s linear infinite;
            display: inline-block;
            vertical-align: middle;
            margin-right: 8px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="register-container">
        <h1 class="register-title">用户注册</h1>
        
        <form id="registerForm">
            <div class="form-group">
                <label for="email" class="form-label">电子邮箱</label>
                <input type="email" id="email" class="form-input" placeholder="请输入邮箱" required>
                <div id="emailError" class="error-message">请输入有效的邮箱地址</div>
            </div>
            
            <div class="form-group">
                <label for="name" class="form-label">用户名</label>
                <input type="text" id="name" class="form-input" placeholder="请输入用户名" required>
                <div id="nameError" class="error-message">用户名不能为空</div>
            </div>
            
            <div class="form-group">
                <label for="password" class="form-label">密码</label>
                <input type="password" id="password" class="form-input" placeholder="请输入密码(至少6位)" required>
                <div id="passwordError" class="error-message">密码至少需要6位</div>
            </div>
            
            <div class="form-group">
                <label for="phone" class="form-label">手机号码</label>
                <input type="tel" id="phone" class="form-input" placeholder="请输入手机号" required>
                <div id="phoneError" class="error-message">请输入有效的手机号</div>
            </div>
            
            <div class="form-group">
                <label for="sex" class="form-label">性别</label>
                <select id="sex" class="form-input" required>
                    <option value="">-- 请选择性别 --</option>
                    <option value="201">男</option>
                    <option value="202">女</option>
                    <option value="203">未知</option>
                </select>
                <div id="sexError" class="error-message">请选择性别</div>
            </div>
            
            <button type="submit" class="register-btn" id="submitBtn">
                <span id="btnText">注册</span>
            </button>
        </form>
    </div>

    <script>
        // 性别常量定义
        const GENDER = {
            MALE: 201,
            FEMALE: 202,
            UNKNOWN: 203
        };

        document.addEventListener('DOMContentLoaded', function() {
            const registerForm = document.getElementById('registerForm');
            const submitBtn = document.getElementById('submitBtn');
            const btnText = document.getElementById('btnText');
            
            // 邮箱验证正则
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            // 手机号验证正则（简单版）
            const phoneRegex = /^1[3-9]\d{9}$/;
            
            registerForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                // 获取表单值
                const email = document.getElementById('email').value.trim();
                const name = document.getElementById('name').value.trim();
                const password = document.getElementById('password').value;
                const phone = document.getElementById('phone').value.trim();
                const sex = parseInt(document.getElementById('sex').value); // 转换为数字类型
                
                // 重置错误提示
                document.querySelectorAll('.error-message').forEach(el => {
                    el.style.display = 'none';
                });
                
                // 验证逻辑
                let isValid = true;
                
                if (!emailRegex.test(email)) {
                    document.getElementById('emailError').style.display = 'block';
                    isValid = false;
                }
                
                if (!name) {
                    document.getElementById('nameError').style.display = 'block';
                    isValid = false;
                }
                
                if (password.length < 6) {
                    document.getElementById('passwordError').style.display = 'block';
                    isValid = false;
                }
                
                if (!phoneRegex.test(phone)) {
                    document.getElementById('phoneError').style.display = 'block';
                    isValid = false;
                }
                
                if (!sex || ![GENDER.MALE, GENDER.FEMALE, GENDER.UNKNOWN].includes(sex)) {
                    document.getElementById('sexError').style.display = 'block';
                    isValid = false;
                }
                
                if (!isValid) return;
                
                // 显示加载状态
                submitBtn.disabled = true;
                btnText.innerHTML = '<span class="loader"></span> 注册中...';
                
                try {
                    // 准备请求数据（使用性别常量）
                    const requestData = {
                        email: email,
                        name: name,
                        password: password,
                        phone: phone,
                        sex: sex// 头像字段留空
                    };
                    
                    // 发送注册请求（增强错误处理）
                    const response = await fetch("/api/user/register", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });

                    // 检查响应内容类型
                    const contentType = response.headers.get('content-type');
                    if (!contentType || !contentType.includes('application/json')) {
                        const text = await response.text();
                        throw new Error(`服务器返回非JSON数据: ${text.substring(0, 100)}`);
                    }

                    const result = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(result.message || `注册失败 (状态码: ${response.status})`);
                    }
                    
                    alert('注册成功！');
                    console.log('注册返回数据:', result);
                    window.location.href = '/login.html'; // 跳转到登录页
                    
                } catch (error) {
                    console.error('注册错误:', error);
                    alert(`注册失败: ${error.message}`);
                } finally {
                    // 重置按钮状态
                    submitBtn.disabled = false;
                    btnText.textContent = '注册';
                }
            });
        });
    </script>
</body>
</html>